package com.users.rn.rncommon.manager;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.Callback;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.modules.core.PermissionListener;
import com.users.rn.rncommon.model.PluginInfo;
import com.users.rn.rncommon.util.ReactConst;

/**
 * @Description:
 * @Author: bluce
 * @Date: 2020/12/3 10:38
 */
public class ALHReactActivityDelegate extends ReactActivityDelegate {
    private ALHReactDelegate mReactDelegate;
    private @Nullable
    PermissionListener mPermissionCallback;
    private @Nullable
    Callback mCallback;

    private ALHReactNativeHost mReactNativeHost;
    private PluginInfo mPluginInfo;
    private boolean isLoaded = false;

    public ALHReactActivityDelegate(Activity activity) {
        super(activity, null);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    }

    @Override
    public ALHReactNativeHost getReactNativeHost() {
        if (mReactNativeHost == null) {
            isLoaded = true;
            mReactNativeHost = ALHReactEnvManager.getInstance().getDebugReactNativeHost();
        }
        return mReactNativeHost;
    }

    public void onFragmentDelegateCreate(ALHReactNativeHost host, PluginInfo pluginInfo) {
        mReactNativeHost = host;
        mPluginInfo = pluginInfo;
        onCreateReactDelegate();
    }

    public ReactRootView loadFragmentApp() {
        if (mReactDelegate != null) {
            mReactDelegate.loadApp(mPluginInfo.getComponentName());
            mReactNativeHost.addComponent(mPluginInfo.getComponentName());
            return mReactDelegate.getReactRootView();
        }
        return null;
    }

    public void onDelegateCreate(ALHReactNativeHost host, PluginInfo pluginInfo) {
        mReactNativeHost = host;
        mPluginInfo = pluginInfo;
        onCreateReactDelegate();
        if (getReactNativeHost() != null && getReactNativeHost().getUseDeveloperSupport() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Get permission to show redbox in dev builds.
            if (!Settings.canDrawOverlays(getContext())) {
                Intent serviceIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getContext().getPackageName()));
                FLog.w(ReactConstants.TAG, ReactConst.REDBOX_PERMISSION_MESSAGE);
                Toast.makeText(getContext(), ReactConst.REDBOX_PERMISSION_MESSAGE, Toast.LENGTH_LONG).show();
                ((Activity) getContext()).startActivityForResult(serviceIntent, ReactConst.REQUEST_OVERLAY_PERMISSION_CODE);
            }
        }

    }

    @Override
    protected void loadApp(String appKey) {
        loadApp();
    }

    public void loadApp() {
        if (mReactDelegate != null) {
            mReactDelegate.loadApp(mPluginInfo.getComponentName());
            getPlainActivity().setContentView(mReactDelegate.getReactRootView());
            mReactNativeHost.addComponent(mPluginInfo.getComponentName());
        }
    }

    protected void onCreateReactDelegate() {
        if (mReactDelegate == null) {
            mReactDelegate = new ALHReactDelegate(getPlainActivity(), getReactNativeHost(), mPluginInfo.getComponentName(), mPluginInfo.getParams());
        }
    }


    @Override
    public boolean onBackPressed() {
        if (mReactDelegate != null) {
            return mReactDelegate.onBackPressed();
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        if (mReactDelegate != null) {
            mReactDelegate.onHostDestroy();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mReactDelegate != null) {
            mReactDelegate.onActivityResult(requestCode, resultCode, data, true);
        }
    }

    @Override
    public void onPause() {
        if (mReactDelegate != null) {
            mReactDelegate.onHostPause();
        }
    }

    @Override
    public void onResume() {
        if (mReactDelegate != null) {
            mReactDelegate.onHostResume();
        }
        if (mCallback != null) {
            mCallback.invoke();
            mCallback = null;
        }
    }

    @Override
    public ReactInstanceManager getReactInstanceManager() {
        if (mReactDelegate != null) {
            return mReactDelegate.getReactInstanceManager();
        } else {
            return null;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mReactDelegate != null) {
            return mReactDelegate.shouldShowDevMenuOrReload(keyCode, event);
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(
            final int requestCode, final String[] permissions, final int[] grantResults) {
        mCallback =
                args -> {
                    if (mPermissionCallback != null
                            && mPermissionCallback.onRequestPermissionsResult(
                            requestCode, permissions, grantResults)) {
                        mCallback = null;
                    }
                };
    }

    @Override
    @TargetApi(Build.VERSION_CODES.M)
    public void requestPermissions(
            String[] permissions, int requestCode, PermissionListener listener) {
        mPermissionCallback = listener;
        getPlainActivity().requestPermissions(permissions, requestCode);
    }
}
